package web.servlet.zy5.login.servlet;

import web.servlet.zy5.login.dao.UserDao;
import web.servlet.zy5.login.dao.UserDaoImpl;
import web.servlet.zy5.login.domin.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author Administrator
 * @Date 2020/5/29 8:29
 **/
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /** 设置post请求编码（解决中文乱码）
         * 获取请求参数*
         * 调用dao层的方法完成登录功能
         * 根据返回值
         * 判断不为空将用户名保存在域对象 转发到successServlet
         * 为空转发到 failServlet*/
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserDao dao = new UserDaoImpl();
        User login = dao.login(username, password);
        if (login != null) {
            /**把用户名保存在域对象
             * 转发*/
            req.setAttribute("username", login.getUsername());
            req.getRequestDispatcher("/successServlet").forward(req, resp);
        } else {
            /** 把错误信息保存在域对象
             * 转发*/
            req.setAttribute("login_error", "用户名或密码错误！");
            req.getRequestDispatcher("/failServlet").forward(req, resp);

        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
